<template>
  <h1>订单列表</h1>
  <div>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键字:">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入关键字"
            clearable
          />
        </el-form-item>
        <el-form-item label="ID">
          <el-input v-model="searchForm.id" placeholder="请输入ID" clearable />
        </el-form-item>
        <el-form-item label="订单状态:">
          <el-select
            v-model="searchForm.orderStatus"
            placeholder="请选择订单状态"
            style="width: 180px"
            clearable
          >
            <el-option label="未支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="待支付" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型:">
          <el-select
            v-model="searchForm.orderType"
            placeholder="请选择订单类型"
            style="width: 180px"
            clearable
          >
            <el-option label="普通订单" :value="1" />
            <el-option label="秒杀订单" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-form-item>
        <el-button type="primary" @click="toAddOrder">新增</el-button>
        <el-button type="danger" @click="deletAll">批量删除</el-button>
        <el-button type="success" @click="exportOrder">导出订单</el-button>
      </el-form-item>
    </div>

    <div>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderId" label="ID" />
        <el-table-column prop="orderNo" label="订单编号" />
        <el-table-column prop="typeName" label="订单类型" />
        <el-table-column prop="userName" label="买家" />
        <el-table-column prop="prodInfo" label="商品名称" />
        <el-table-column label="商品图片" width="150px">
          <template #default="scope">
            <el-image
              v-for="item in scope.row.imageList"
              :src="item"
              :key="item"
              style="width: 50px; height: 50px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="orderAmount" label="订单金额" />
        <el-table-column prop="orderStatus" label="订单状态">
          <template #default="scope">
            <span v-if="scope.row.orderStatus == 0">未支付</span>
            <span v-if="scope.row.orderStatus == 1">已支付</span>
            <span v-if="scope.row.orderStatus == 2">待发货</span>
          </template>
        </el-table-column>

        <el-table-column prop="payTime" label="支付时间" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <el-button type="primary">查看记录 </el-button>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 20px">
      <div class="demo-pagination-block" style="width: 800px; margin: 0 auto">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 弹框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="新增订单" width="600">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item label="选择商品" prop="prodId">
            <el-select v-model="form.prodId" placeholder="请选择商品" clearable>
              <el-option
                v-for="item in prodIndolist"
                :label="item.prodName"
                :value="item.infoId"
                :key="item.infoId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="购买数量" prop="buyNum">
            <el-input v-model="form.buyNum" />
          </el-form-item>

          <el-button type="success" @click="buyProd">购买</el-button>
          <el-form-item label="">
            <el-table :data="gridData">
              <el-table-column property="infoId" label="商品ID" />
              <el-table-column property="prodName" label="商品名称" />
              <el-table-column property="prodPrice" label="商品价格" />
              <el-table-column property="buyNum" label="购买数量" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="danger" @click="deleteInfo(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          总金额:{{ amount }}元
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getOrderList,
  deleteAllOrder,
  getProdInfoList,
  addOrder,
} from "@/api/api";
import { useRouter } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";
import type { TableInstance } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const router = useRouter();
const tableData = ref([]);
//商品明细
const gridData = ref([]);
const multipleSelection = ref<any[]>([]);
const total = ref(0);
const dialogFormVisible = ref(false);
const ruleFormRef = ref<FormInstance>();
const prodIndolist = ref([]);
const formLabelWidth = "140px";
const form = ref({
  buyNum: 1,
  costPrice: null,
  createBy: null,
  createTime: null,
  infoId: null,
  prodId: null,
  prodName: null,
  prodPrice: null,
  prodSku: null,
  prodStock: null,
  updateBy: null,
  updateTime: null,
});

//提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addOrder(gridData.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};
//表单校验
const rules = ref<FormRules<any>>({
  prodId: [{ required: true, message: "选择商品不能为空", trigger: "blur" }],
  buyNum: [{ required: true, message: "购买数量不能为空", trigger: "blur" }],
});

//总金额
const amount = ref(0.0);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  id: null,
  keyWord: null,
  orderStatus: null,
  orderType: null,
});

//删除商品
const deleteInfo = (row: any) => {
  gridData.value.forEach((item, index) => {
    if (item.infoId == row.infoId) {
      gridData.value.splice(item, 1);
    }
  });
  amount.value = 0;
  gridData.value.forEach((item) => {
    amount.value += item.prodPrice;
  });
};
//购买商品
const buyProd = () => {
  prodIndolist.value.forEach((item) => {
    if (item.infoId == form.value.prodId) {
      item.buyNum = form.value.buyNum;
      gridData.value.push(item);
      amount.value += item.prodPrice * item.buyNum;
    }
  });
};

//新增弹框
const toAddOrder = () => {
  dialogFormVisible.value = true;
};

//导出订单
const exportOrder = () => {
  let ids = "";
  tableData.value.forEach((item) => {
    if (ids == "") {
      ids = item.orderId;
    } else {
      ids = ids + "," + item.orderId;
    }
    //拼接路径
    let url = "http://localhost:9011/goods/order/exportOrder/" + ids;
    window.open(url);
  });
};

//多选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
//批量删除
const deletAll = () => {
  ElMessageBox.confirm("数据删除后无法恢复,您确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteAllOrder(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};

//分页回调
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};
const loadList = () => {
  getOrderList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
onMounted(() => {
  loadList();
  //获取所有商品明细
  getProdInfoList().then((res) => {
    if (res.data.code == 200) {
      prodIndolist.value = res.data.data;
    }
  });
});
</script>

<style scoped></style>
